/******************************************************************************
 *      Mestrado em Ciência da Computação - UFMS
 *		Redes de Computadores - Prof. Dr. Ronaldo Alves Ferreira
 *		Alunos: Geraldo Landre, Marcel Tolentino, Vinícius Bueno
 *****************************************************************************/
/* tcpwakeup.c - tcpwakeup */

#include "tcpfms.h"
#include "tcb.h"
#include "tcp.h"

/*------------------------------------------------------------------------
 *  tcpwakeup -  acorda processos em sleeping para TCP, se necessario
 *	NB: Called with tcb_mutex HELD
 *------------------------------------------------------------------------
 */
int tcpwakeup(int type, struct tcb *ptcb)
{
	int	freelen;
        int     count;
//	STATWORD	ps;
//	disable(ps);
        
	if (type & READERS) 
        {

                sem_getvalue(&(ptcb->tcb_rsema), &count);
		if (((ptcb->tcb_flags & TCBF_RDONE) ||
		    ptcb->tcb_rbcount > 0 ||
		    (ptcb->tcb_flags & TCBF_RUPOK)) &&
		    count <= 0)
			sem_post(&(ptcb->tcb_rsema));
	}
	if (type & WRITERS) 
        {
                sem_getvalue(&(ptcb->tcb_ssema), &count);
		freelen = ptcb->tcb_sbsize - ptcb->tcb_sbcount;
		if (((ptcb->tcb_flags & TCBF_SDONE) || freelen > 0) &&
		    count <= 0)
			sem_post(&(ptcb->tcb_ssema));
		/* special for abort */
                sem_getvalue(&(ptcb->tcb_ocsem), &count);
		if (ptcb->tcb_error && count > 0)
			sem_post(&(ptcb->tcb_ocsem));
	}
//	restore(ps);
	return OK;
}
